package kassiopeia.agent.log;

import kassiopeia.agent.AgentIDHolder;
import kassiopeia.commons.log.Log;
import kassiopeia.commons.log.LogLevel;
import org.apache.log4j.Level;
import org.apache.log4j.spi.LocationInfo;
import org.apache.log4j.spi.LoggingEvent;
import static com.google.common.base.Preconditions.*;

public class LogFactory {

    public static final LogLevel DEFAULT_LEVEL = LogLevel.INFO;

    public static Log getLog(LoggingEvent log4jEvent) {
        checkNotNull(log4jEvent, "Received null event from log4j - something is wrong...");

        Log log = new Log();

        log.setAgentId(AgentIDHolder.getThisAgentId());
        log.setLevel(convertFromLog4jLevel(log4jEvent.getLevel()));
        log.setMessage(getLogMessage(log4jEvent));
        log.setTimestamp(log4jEvent.getTimeStamp());

        LocationInfo info = log4jEvent.getLocationInformation();
        if(info != null) {
            log.setClassName(info.getClassName());
        } else {
            log.setClassName("unknown");
        }
        return log;
    }

    private static LogLevel convertFromLog4jLevel(Level log4jLevel) {
        if(log4jLevel == Level.TRACE) return LogLevel.TRACE;
        if(log4jLevel == Level.DEBUG) return LogLevel.DEBUG;
        if(log4jLevel == Level.INFO) return LogLevel.INFO;
        if(log4jLevel == Level.WARN) return LogLevel.WARN;
        if(log4jLevel == Level.ERROR) return LogLevel.ERROR;
        if(log4jLevel == Level.FATAL) return LogLevel.FATAL;
        return DEFAULT_LEVEL;
    }

    private static String getLogMessage(LoggingEvent log4jEvent) {
        Object messageObj = log4jEvent.getMessage();
        if(messageObj == null) return "";
        return messageObj.toString();
    }
}
